<template>
	<view class="container">
		<!-- 购物车为空时显示 -->
		<view v-if="cartList.length === 0" class="empty-cart">
			<image src="/static/empty-cart.png" class="empty-img"></image>
			<text class="empty-text">购物车为空</text>
			<button class="go-shopping" @click="navigateToIndex">去购物</button>
		</view>

		<!-- 购物车列表 -->
		<view v-else class="cart-container">
			<!-- 全选 -->
			<view class="cart-header">
				<view class="checkbox-wrapper" @click="toggleAllSelect">
					<view class="checkbox" :class="{ 'checked': isAllSelected }"></view>
					<text class="all-select-text">全选</text>
				</view>
				<view class="edit-btn" @click="toggleEdit">{{ isEditing ? '完成' : '编辑' }}</view>
			</view>

			<!-- 商品列表 -->
			<view class="cart-list">
				<view v-for="(item, index) in cartList" :key="item.id" class="cart-item">
					<view class="checkbox-wrapper" @click="toggleSelect(index)">
						<view class="checkbox" :class="{ 'checked': item.selected }"></view>
					</view>

					<view class="item-content">
						<image :src="item.goods_thumb" class="goods-img"></image>
						<view class="goods-info">
							<text class="goods-name">{{ item.goods_name }}</text>
							<text class="goods-spec">{{ item.selected_item_name }}</text>
							<view class="price-num">
								<text v-if="!isEditing" class="goods-price">&yen;{{ item.goods_price }}</text>
								<view v-if="!isEditing" class="num-control">
									<view class="num-btn minus" @click="decreaseNum(index)"
										:class="{ 'disabled': item.cart_num <= 1 }">-</view>
									<text class="num">{{ item.cart_num }}</text>
									<view class="num-btn plus" @click="increaseNum(index)">+</view>
								</view>
								<view v-if="isEditing" class="delete-btn" @click="deleteCartItem(index)">删除</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 结算 -->
			<view class="cart-footer">
				<view v-if="!isEditing" class="total-price">
					<text>合计：</text>
					<text class="price">&yen;{{ totalPrice }}</text>
				</view>
				<view v-if="!isEditing">
					<button class="checkout-btn" :disabled="selectedCount === 0"
						@click="checkout">结算({{ selectedCount }})</button>
				</view>
				<view v-if="isEditing">
					<button class="delete-btn" @click="deleteSelectedItems"
						:disabled="selectedCount === 0">删除选中({{ selectedCount }})</button>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore">加载中...</view>
	</view>
</template>

<script>
	import {
		userCart,
		changeNum,
		delCart
	} from '../../api/request';
	export default {
		data() {
			return {
				cartList: [],
				page: 1,
				hasMore: true,
				isAllSelected: false,
				selectedCount: 0,
				totalPrice: 0,
				isEditing: false
			}
		},
		onShow() {
			if (!uni.getStorageSync('token')) {
				uni.redirectTo({
					url: '/pages/register/login'
				})
				return;
			}
			this.getCartList();
		},
		onReachBottom() {
			// 上拉加载更多
			if (this.hasMore) {
				this.page++;
				this.getCartList();
			}
		},
		methods: {
			// 获取购物车列表
			async getCartList() {
				try {
					const res = await userCart({
						page: this.page
					});
					if (res.code === 1) {
						const newData = res.data.rows.flatMap(row => row.list);
						// 为每个商品添加selected属性，默认为false
						newData.forEach(item => {
							item.selected = false;
						});

						if (this.page === 1) {
							this.cartList = newData;
						} else {
							this.cartList = [...this.cartList, ...newData];
						}

						// 判断是否还有更多数据
						this.hasMore = this.cartList.length < res.data.total;
					} else {
						uni.showToast({
							title: res.msg || '获取购物车失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取购物车列表失败:', error);
				}
			},

			// 切换全选
			toggleAllSelect() {
				this.isAllSelected = !this.isAllSelected;
				this.cartList.forEach(item => {
					item.selected = this.isAllSelected;
				});
				this.calculateTotal();
			},

			// 切换单个商品选择状态
			toggleSelect(index) {
				this.cartList[index].selected = !this.cartList[index].selected;
				// 检查是否全选
				this.isAllSelected = this.cartList.every(item => item.selected);
				this.calculateTotal();
			},

			// 增加商品数量
			async increaseNum(index) {
				try {
					const res = await changeNum({
						cart_id: this.cartList[index].id,
						type: 1
					});
					if (res.code === 1) {
						this.cartList[index].cart_num++;
						this.calculateTotal();
					} else {
						uni.showToast({
							title: res.msg || '增加数量失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('增加商品数量失败:', error);
					uni.showToast({
						title: '增加数量失败',
						icon: 'none'
					});
				}
			},

			// 减少商品数量
			async decreaseNum(index) {
				if (this.cartList[index].cart_num > 1) {
					try {
						const res = await changeNum({
							cart_id: this.cartList[index].id,
							type: 2
						});
						if (res.code === 1) {
							this.cartList[index].cart_num--;
							this.calculateTotal();
						} else {
							uni.showToast({
								title: res.msg || '减少数量失败',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('减少商品数量失败:', error);
						uni.showToast({
							title: '减少数量失败',
							icon: 'none'
						});
					}
				}
			},

			// 删除单个购物车商品
			async deleteCartItem(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await delCart({
									ids: this.cartList[index].id
								});
								if (result.code === 1) {
									this.cartList.splice(index, 1);
									this.calculateTotal();
									// 检查是否全选
									this.isAllSelected = this.cartList.every(item => item.selected);
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: result.msg || '删除失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('删除购物车商品失败:', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 批量删除选中的购物车商品
			async deleteSelectedItems() {
				const selectedIds = this.cartList
					.filter(item => item.selected)
					.map(item => item.id)
					.join(',');

				if (!selectedIds) {
					uni.showToast({
						title: '请选择要删除的商品',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '提示',
					content: '确定要删除选中的商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await delCart({
									ids: selectedIds
								});
								if (result.code === 1) {
									// 过滤掉已删除的商品
									this.cartList = this.cartList.filter(item => !item.selected);
									this.isAllSelected = false;
									this.calculateTotal();
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: result.msg || '删除失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('批量删除购物车商品失败:', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 切换编辑模式
			toggleEdit() {
				this.isEditing = !this.isEditing;
				// 如果退出编辑模式，取消全选
				if (!this.isEditing) {
					this.isAllSelected = false;
					this.cartList.forEach(item => {
						item.selected = false;
					});
					this.calculateTotal();
				}
			},

			// 计算总价和选中数量
			calculateTotal() {
				let total = 0;
				let count = 0;
				this.cartList.forEach(item => {
					if (item.selected) {
						total += Number(item.goods_price) * item.cart_num;
						count++;
					}
				});
				this.totalPrice = total.toFixed(2);
				this.selectedCount = count;
			},

			// 结算
			checkout() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择商品',
						icon: 'none'
					});
					return;
				}
				// 获取选中商品的cart_ids
				const cartIds = this.cartList
					.filter(item => item.selected)
					.map(item => item.id)
					.join(',');
				// 跳转到确认订单页面
				uni.navigateTo({
					url: `/pages/order/sureOrder?cart_ids=${cartIds}`
				});
			},

			// 跳转到首页
			navigateToIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding-bottom: 100rpx;
		min-height: 100vh;
		background-color: #f5f5f5;

		.empty-cart {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100vh;

			.empty-img {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
			}

			.empty-text {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 40rpx;
			}

			.go-shopping {
				width: 200rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #ff6b00;
				color: #fff;
				border-radius: 40rpx;
				font-size: 28rpx;
			}
		}

		.cart-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;

			.checkbox-wrapper {
				display: flex;
				align-items: center;

				.checkbox {
					width: 32rpx;
					height: 32rpx;
					border: 2rpx solid #999;
					border-radius: 50%;
					margin-right: 10rpx;

					&.checked {
						border-color: #ff6b00;
						background-color: #ff6b00;
						position: relative;

						&::after {
							content: '';
							position: absolute;
							left: 6rpx;
							top: 10rpx;
							width: 12rpx;
							height: 6rpx;
							border-left: 2rpx solid #fff;
							border-bottom: 2rpx solid #fff;
							transform: rotate(-45deg);
						}
					}
				}

				.all-select-text {
					font-size: 28rpx;
					color: #333;
				}
			}

			.edit-btn {
				font-size: 28rpx;
				color: #333;
			}
		}

		.cart-list {
			// padding: 0 30rpx;

			.cart-item {
				display: flex;
				padding: 20rpx;
				border-bottom: 1rpx solid #eee;
				background-color: #fff;

				.checkbox-wrapper {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 60rpx;

					.checkbox {
						width: 32rpx;
						height: 32rpx;
						border: 2rpx solid #999;
						border-radius: 50%;

						&.checked {
							border-color: #ff6b00;
							background-color: #ff6b00;
							position: relative;

							&::after {
								content: '';
								position: absolute;
								left: 6rpx;
								top: 10rpx;
								width: 12rpx;
								height: 6rpx;
								border-left: 2rpx solid #fff;
								border-bottom: 2rpx solid #fff;
								transform: rotate(-45deg);
							}
						}
					}
				}

				.item-content {
					display: flex;
					flex: 1;

					.goods-img {
						width: 160rpx;
						height: 160rpx;
						border-radius: 8rpx;
						margin-right: 20rpx;
					}

					.goods-info {
						flex: 1;

						.goods-name {
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
							font-size: 28rpx;
							color: #333;
							margin-bottom: 10rpx;
						}

						.goods-spec {
							font-size: 24rpx;
							color: #999;
							margin-bottom: 20rpx;
						}

						.price-num {
							display: flex;
							justify-content: space-between;
							align-items: center;

							.goods-price {
								font-size: 32rpx;
								color: #ff6b00;
								font-weight: bold;
							}

							.num-control {
								display: flex;
								align-items: center;

								.num-btn {
									width: 48rpx;
									height: 48rpx;
									border: 1rpx solid #ddd;
									text-align: center;
									line-height: 48rpx;
									font-size: 36rpx;

									&.minus {
										border-right: none;
										border-top-left-radius: 8rpx;
										border-bottom-left-radius: 8rpx;
									}

									&.plus {
										border-left: none;
										border-top-right-radius: 8rpx;
										border-bottom-right-radius: 8rpx;
									}

									&.disabled {
										color: #ccc;
									}
								}

								.num {
									width: 56rpx;
									height: 48rpx;
									border-top: 1rpx solid #ddd;
									border-bottom: 1rpx solid #ddd;
									text-align: center;
									line-height: 48rpx;
									font-size: 28rpx;
								}
							}

							.delete-btn {
								padding: 8rpx 20rpx;
								background-color: #ff4d4f;
								color: #fff;
								border-radius: 8rpx;
								font-size: 28rpx;
							}
						}
					}
				}
			}
		}

		.cart-footer {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-top: 1rpx solid #eee;

			.total-price {
				font-size: 28rpx;
				color: #333;

				.price {
					font-size: 32rpx;
					color: #ff6b00;
					font-weight: bold;
					margin-left: 10rpx;
				}
			}

			.checkout-btn {
				width: 220rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #ff6b00;
				color: #fff;
				border-radius: 40rpx;
				font-size: 28rpx;

				&.disabled {
					background-color: #ccc;
				}
			}

			.delete-btn {
				width: 220rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: #ff4d4f;
				color: #fff;
				border-radius: 40rpx;
				font-size: 28rpx;

				&.disabled {
					background-color: #ccc;
				}
			}
		}

		.load-more {
			text-align: center;
			padding: 20rpx 0;
			font-size: 28rpx;
			color: #999;
		}
	}
</style>